﻿using Cocbook_DAL;
using Cocbook_DTO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Drawing.Printing;
using GenCode128;
namespace Cocbook___modul_sale
{
    public partial class frmMain : DevComponents.DotNetBar.Metro.MetroForm
    {
        public frmMain()
        {
            InitializeComponent();
            LoaddgvBookSearch();
        }

        public int editRow = 0;
        public bool updateBill = false;
        public Bill oBill = new Bill();
        public static Staff staff;
        public static bool status;
        public BillDAL billDAL = new BillDAL();
        public BookDAL bookDAL = new BookDAL();
        public ProjectDAL projectDAL = new ProjectDAL();
        public static Project project = new Project();
        public Project_BookDAL pbDAL = new Project_BookDAL();
        public static List<SBook> lsb = null;
        public List<Bill_Book> billdetail = new List<Bill_Book>();
        public Customer customer = new Customer(1,0, "Khách vãng lai", DateTime.Parse("1/1/1800"), "null", " ", " ","", 0);
        public Book book = new Book();
        public int row = -1;
        public bool addMode = true;
        public bool logout = false;
        public int billHisEdittingRow = -1;


        private void frmMain_Load(object sender, EventArgs e)
        {            
            sbtConnectStatus.Value = status;
            lblProjectID.Text = project.ProjectName;
            lblStaffname.Text = staff.StaffName;
            DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
            btn.HeaderText = "Xóa";
            btn.Text = "Xóa";
            btn.Name = "btnDelete";
            btn.Width = 33;
            btn.UseColumnTextForButtonValue = true;
            dgvBill.Columns.Add(btn);
            dgvBill.ContextMenuStrip = RightClickMenu;
        }


        #region Tabsale

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtCash.Checked == false)
            {
                txtChange.Text = "0";
                txtPaid.Text = "0";
                txtPaid.Enabled = false;
            }
            else
            {
                txtPaid.Enabled = true;
                txtPaid.Text = txtTotal.Text;
                txtChange.Text = "0";
                txtPaid.Focus();
            }
        }

        public void ReadBarcode()
        {
            addMode = true;
            switch (txtBarcode.Text.Length)
            {
                case 7:
                    LoadOldBill();
                    break;
                case 9:
                    LoadCustomer();
                    break;
                case 10:
                    if (dgvBill.RowCount == 0) lblBillID.Text = ShowBillID((billDAL.GetMaxBillID() + 1));
                    addMode = true;
                    LoadBook();
                    break;
                case 11:
                    if (dgvBill.RowCount == 0) lblBillID.Text = ShowBillID((billDAL.GetMaxBillID() + 1));
                    addMode = true;
                    LoadBook();
                    break;
                case 12:
                    if (dgvBill.RowCount == 0) lblBillID.Text = ShowBillID((billDAL.GetMaxBillID() + 1));
                    addMode = true;
                    LoadBook();
                    break;
                case 13:
                    if (dgvBill.RowCount == 0) lblBillID.Text = ShowBillID((billDAL.GetMaxBillID() + 1));
                    addMode = true;
                    LoadBook();
                    break;
            }
        }

        public void LoadOldBill()
        {
            oBill = billDAL.GetBillByID(Convert.ToInt16(txtBarcode.Text));
            if (oBill == null)
            {
                txtBarcode.Clear();
                txtBarcode.Focus();
                lblValidate.Text = "Không tìm thấy mã hóa đơn này, vui lòng nhập lại";
                highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
            }
            else
            {
                lblBillID.Text = ShowBillID(oBill.BillID);
                Bill_BookDAL bbDAL = new Bill_BookDAL();
                List<Bill_Book> lbb = bbDAL.GetBill_BookByBillID(oBill.BillID);
                dgvBill.Rows.Clear();
                billdetail = new List<Bill_Book>();
                for (int i = 0; i < lbb.Count; i++)
                {
                    billdetail.Add(lbb[i]);
                    dgvBill.Rows.Add(i + 1, lbb[i].Book.ISBN, lbb[i].Book.Title, lbb[i].Copy, lbb[i].Book.Price, lbb[i].Discount, lbb[i].Book.Price * (100 - lbb[i].Discount) / 100);
                    dgvBill.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
                }
                dgvBill.Refresh();
                customer = oBill.Customer;
                lblCustomerID.Text = ShowCustomerID(oBill.Customer.CMND);
                lblCustomerName.Text = oBill.Customer.CName;
                lblCustomerBonus.Text = oBill.Customer.Points.ToString();
                txtBarcode.Clear();
                txtBarcode.Focus();
                updateBill = true;
            }
        }

        public string ShowCustomerID(int id)
        {
            string result = "000000000" + id.ToString();
            result = result.Substring(result.Length - 9);
            return result;
        }

        public void LoadCustomer()
        {
            Customer c = new Customer();
            CustomerDAL cDAL = new CustomerDAL();
            c = cDAL.GetCustomerByCMND(Convert.ToInt32(txtBarcode.Text));
            if (c == null)
            {
                txtBarcode.Clear();
                txtBarcode.Focus();
                lblValidate.Text = "Không tồn tại mã khách hàng này, vui lòng liên hệ bộ phận chăm sóc khách hàng để cập nhật";
                highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
            }
            else
            {
                if (lblCustomerID.Text == "000000000")
                {
                    lblCustomerID.Text = ShowCustomerID(c.CMND);
                    lblCustomerName.Text = c.CName;
                    customer = c;
                    lblCustomerBonus.Text = c.Points.ToString();
                    txtBarcode.Clear();
                    txtBarcode.Focus();
                }
                else
                {
                    if (MessageBox.Show("Hóa đơn hiện tại thuộc về khách hàng " + lblCustomerName.Text + ". Bạn có muốn thay thế hay không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        customer = c;
                        lblCustomerID.Text = ShowCustomerID(c.CMND);
                        lblCustomerName.Text = c.CName;
                        lblCustomerBonus.Text = c.Points.ToString();
                        txtBarcode.Clear();
                        txtBarcode.Focus();
                    }
                    else
                    {
                        txtBarcode.Clear();
                        txtBarcode.Focus();
                    }
                }
            }
        }

        public int GetBookIndex_dgvBill(Int64 ISBN)
        {
            if (dgvBill.RowCount == 0)
            {
                return 0;
            }
            else
            {
                int result = dgvBill.RowCount;
                int i = 0;
                foreach (DataGridViewRow row in dgvBill.Rows)
                {
                    if (row.Cells[1].Value.ToString() == ISBN.ToString())
                    {
                        result = i;
                        break;
                    }
                    else
                    {
                        i = i + 1;
                    }
                }
                return result;
            }
        }

        public void AddBookToBill(Int64 isbn, string name, int copy, double price, double discount)
        {
            int id = GetBookIndex_dgvBill(isbn);
            dgvBill.Columns[7].Width = 35;
            if (id == dgvBill.RowCount || dgvBill.RowCount == 0)
            {

                dgvBill.Rows.Add(id + 1, isbn, name, copy, price, discount, price * (100 - discount) / 100);
            }
            else
            {
                dgvBill.Rows[id].Cells[3].Value = (Convert.ToInt16(dgvBill.Rows[id].Cells[3].Value) + copy);
            }
            dgvBill.Refresh();
        }

        public void LoadBook()
        {
            book = bookDAL.GetBookByISBN(Convert.ToInt64(txtBarcode.Text));
            if (book == null)
            {
                txtBarcode.Clear();
                highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                lblValidate.Text = "Mã vạch sai. Vui lòng nhập lại.";
                txtBarcode.Focus();
            }
            else
            {
                Project_Book pro_book = new Project_Book();
                pro_book = new Project_Book();
                pro_book = pbDAL.GetProject_BookByID(project.ProjectID, book.BookID);
                if (pro_book == null)
                {
                    highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                    txtTitle.Text = book.Title;
                    txtCopy.Text = "1";
                    txtCopy.Focus();
                    txtCopy.SelectAll();
                    lblValidate.Text = "Mã sách chưa được kiểm kê!";
                }
                else
                {
                    if (!addMode)
                    {
                        
                        txtTitle.Text = book.Title;
                        txtDiscount.Text = pro_book.Discount.ToString();
                        txtCopy.Text = "1";
                        txtCopy.Focus();
                        txtCopy.SelectAll();
                    }
                    else
                    {
                        int copy = 1;
                        int id = GetBookIndex_dgvBill(book.ISBN);
                        if (id == dgvBill.RowCount || dgvBill.RowCount == 0)
                        {
                            if (copy > (new Project_BookDAL()).GetQuatityInWareHouseBookByBookID(project.ProjectID, book.BookID))
                            {
                                txtBarcode.Focus();
                                txtBarcode.SelectAll();
                                lblValidate.Text = "Số lượng nhiều hơn số lượng có trong kho.";
                            }
                            else
                            {
                                Bill_Book bb = new Bill_Book(null, book, 0, 0);
                                billdetail.Add(bb);
                                AddBookToBill(book.ISBN, book.Title, copy, book.Price, pro_book.Discount);
                                txtBarcode.Clear();
                            }
                        }
                        else
                        {
                            if (Convert.ToInt16(copy) > (new Project_BookDAL()).GetQuatityInWareHouseBookByBookID(project.ProjectID, book.BookID) - Convert.ToInt16(dgvBill.Rows[id].Cells[3].Value))
                            {
                                txtBarcode.Focus();
                                txtBarcode.SelectAll();
                                lblValidate.Text = "Số lượng nhiều hơn số lượng có trong kho.";
                            }
                            else
                            {
                                Bill_Book bb = new Bill_Book(null, book, 0, 0);
                                billdetail.Add(bb);
                                AddBookToBill(book.ISBN, book.Title, copy, book.Price, pro_book.Discount);
                                txtBarcode.Clear();
                            }
                        }
                    }
                }
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (superTabControl1.SelectedTab == tabSale)
            {
                switch (keyData)
                {
                    case Keys.F1:
                        btnPrint_Click(null, null);
                        break;
                    case Keys.F2:
                        btnClear_Click(null, null);
                        break;
                    case Keys.Escape:
                        txtDiscount.Clear();
                        txtBarcode.Clear();
                        txtTitle.Clear();
                        txtCopy.Clear();
                        book = new Book();
                        break;
                }
            }
            return base.ProcessDialogKey(keyData);
        }

        #region Print
        
        public void PrintTheBill()
        {
            PrintDocument doc = new PrintDocument();
            doc.PrintPage += new PrintPageEventHandler(Doc_print);
            doc.Print();
        }
        
        private void Doc_print(object sender, PrintPageEventArgs e)
        {
            Font time = new Font("Times New Roman", 11);
            Font time2 = new Font("Consolas", 7);
            Graphics g = e.Graphics;
            Image logo = System.Drawing.Bitmap.FromFile(@"logo.bmp");
            float lpg = 0;
            float ypos = 0;
            float tmargin = e.MarginBounds.Top;
            lpg = e.MarginBounds.Height / time.GetHeight(g);
            g.DrawImage(logo, 7, 15);
            g.DrawString("Công ty Cổ Phần COCBOOK", time, Brushes.Black, 5, 75, new StringFormat());
            ypos = 75 + time.GetHeight(g);
            g.DrawString("   www.cocbook.vn | fb/cocbook", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g) + 5;
            g.DrawString("     0939646679 | 0839918488", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g) + 5;
            g.DrawString("_________________________________", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Nhân viên: "+lblStaffname.Text, time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Tên hàng |CK |SL |Giá |Thành tiền", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("----------------------------------", time2, Brushes.Black, 5, ypos, new StringFormat());
            /////////////////////////
            int total = 0;
            for (int i = 0; i < dgvBill.RowCount; i++)
            {
                ypos = ypos + time2.GetHeight(g);
                if (dgvBill[2, i].Value.ToString().Length < 30)
                {
                    g.DrawString(dgvBill[2, i].Value.ToString() + "... ", time2, Brushes.Black, 5, ypos, new StringFormat());
                }
                else
                {
                    g.DrawString(dgvBill[2, i].Value.ToString().Substring(0, 30) + "... ", time2, Brushes.Black, 5, ypos, new StringFormat());
                }
                ypos = ypos + time2.GetHeight(g);
                total += Convert.ToInt32(dgvBill[3, i].Value);
                g.DrawString("          " + dgvBill[5, i].Value.ToString() + "  " + dgvBill[3, i].Value.ToString() + "  " + dgvBill[4, i].Value.ToString() + "  " +
                            (Convert.ToInt32(dgvBill[4, i].Value) * Convert.ToInt32(dgvBill[3, i].Value) * (100 - Convert.ToInt32(dgvBill[5, i].Value))/100).ToString(), time2, Brushes.Black, 5, ypos, new StringFormat());
            }
            /////////////////////////
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("-------------------------------------", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Tổng:       " + total + "       " + txtTotal.Text, time, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time.GetHeight(g);
            g.DrawString(DateTime.Now.ToString(), time2, Brushes.Black, 5, ypos, new StringFormat());
            Image billCode = Code128Rendering.MakeBarcodeImage(lblBillID.Text, 1, true);

            ypos = ypos + time2.GetHeight(g);
            g.DrawImage(billCode, 10, ypos);

            ypos = ypos + 20;
            g.DrawString(lblBillID.Text, time2, Brushes.Black, 5, ypos, new StringFormat());

            billCode = Code128Rendering.MakeBarcodeImage(lblCustomerID.Text, 1, true);

            ypos = ypos + time2.GetHeight(g)+5;
            g.DrawImage(billCode, 10, ypos);
            ypos = ypos + 20;
            g.DrawString(lblCustomerID.Text, time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("_______________________________________", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Cocbook Cảm ơn bạn đã mua sách", time2, Brushes.Black, 5, ypos, new StringFormat());
        }
        
        #endregion

        private void btnPrint_Click(object sender, EventArgs e)
        {
            Connection con = new Connection();
            if (con.CheckConnection())
            {
                int bonus = 1;
                sbtConnectStatus.Value = true;
                if (rbtBonus.Checked)
                {
                    bonus = 2;
                    txtChange.Text = "0";
                }
                if (double.Parse(txtChange.Text) < 0)
                {
                    txtPaid.Focus();
                    txtPaid.SelectAll();
                    MessageBox.Show("Số tiền của khách đưa không được nhỏ hơn thành tiền");

                }
                else
                {
                    if (dgvBill.RowCount == 0)
                    {
                        if (updateBill)
                        {
                            if (MessageBox.Show("Hóa đơn hiện đang rỗng. Bạn có muốn xóa hẵn hóa đơn này không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                            {
                                (new Bill_BookDAL()).DeleteBill_BookByBillID(Convert.ToInt32(lblBillID.Text));
                                (new BillDAL()).DeleteBill(Convert.ToInt32(lblBillID.Text));
                                ClearAll();
                            }
                        }
                        MessageBox.Show("Danh sách rỗng!!!!!");
                        txtBarcode.Focus();
                    }
                    else
                    {
                        if (updateBill)
                        {

                            Bill b = new Bill(Convert.ToInt32(lblBillID.Text), project, customer, staff, DateTime.Now, Convert.ToDouble(txtTotal.Text), Convert.ToDouble(txtPaid.Text), bonus);
                            billDAL.UpdateBill(b);
                            Bill_BookDAL bbDAL = new Bill_BookDAL();
                            bbDAL.DeleteBill_BookByBillID(b.BillID);
                            for (int i = 0; i < dgvBill.RowCount; i++)
                            {
                                billdetail[i].Bill = b;
                                billdetail[i].Copy = Convert.ToInt16(dgvBill[3, i].Value);
                                billdetail[i].Discount = Convert.ToDouble(dgvBill[3, i].Value);
                                bbDAL.CreateBill_Book(billdetail[i]);
                            }
                            if (customer.CustomerID != 1)
                            {
                                customer.Points = customer.Points + Convert.ToInt32(b.Total - oBill.Total);
                                CustomerDAL customerDAL = new CustomerDAL();
                                customerDAL.UpdateCustomer(customer);
                            }
                            updateBill = false;
                            PrintTheBill();
                            PrintTheBill();
                            ClearAll();
                        }
                        else
                        {
                            DateTime date = DateTime.Now;
                            Bill b = new Bill(Convert.ToInt16(lblBillID.Text), project, customer, staff, date , Convert.ToDouble(txtTotal.Text), Convert.ToDouble(txtPaid.Text), bonus);
                            billDAL.CreateBill(b);
                            b.BillID = (new BillDAL()).GetBillIDByDateTime(date);
                            lblBillID.Text = b.BillID.ToString();
                            Bill_BookDAL bbDAL = new Bill_BookDAL();
                            for (int i = 0; i < dgvBill.RowCount; i++)
                            {
                                billdetail[i].Bill = b;
                                billdetail[i].Copy = Convert.ToInt16(dgvBill[3, i].Value);
                                billdetail[i].Discount = Convert.ToDouble(dgvBill[5, i].Value);
                                bbDAL.CreateBill_Book(billdetail[i]);
                            }
                            if (customer.CustomerID != 1)
                            {
                                customer.Points = customer.Points + Convert.ToInt32(b.Total);
                                CustomerDAL customerDAL = new CustomerDAL();
                                customerDAL.UpdateCustomer(customer);
                            }
                            PrintTheBill();
                            PrintTheBill();
                            ClearAll();
                        }
                    }
                }
            }
            else
            {
                sbtConnectStatus.Value = false;
                MessageBox.Show("Không thể kết nối với Server!", "Connect error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                frmConnectionError frm = new frmConnectionError();
                frm.ShowDialog();
                sbtConnectStatus.Value = status;
            }
        }
        
        public void GetBillID()
        {
            lblBillID.Text = ShowBillID((billDAL.GetMaxBillID() + 1));
        }
        public void ClearAll()
        {
            dgvBill.Rows.Clear();
            txtBarcode.Clear();
            txtTotal.Text = "0";
            txtPaid.Text = "0";
            txtChange.Text = "0";
            rbtCash.Checked = true;
            lblCustomerID.Text = "000000000";
            lblCustomerBonus.Text = "0";
            lblCustomerName.Text = "Khách vãng lai";
            GetBillID();
            txtBarcode.Focus();
            book = new Book();
            billdetail = new List<Bill_Book>();
        }

        #endregion














        private void btnClear_Click(object sender, EventArgs e)
        {
            DialogResult tb = (MessageBox.Show("Bạn xóa  danh sách không ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning));
            if (tb == DialogResult.Yes)
            {
                ClearAll();
            }
        }
        

        public double getTotal()
        {
            double sum = 0;
            for (int i = 0; i < dgvBill.RowCount; i++)
            {
                sum = sum + (Convert.ToDouble(dgvBill.Rows[i].Cells[4].Value) * (100-Convert.ToDouble(dgvBill.Rows[i].Cells[5].Value))/100) * Convert.ToDouble(dgvBill.Rows[i].Cells[3].Value);
            }
            return sum;
        }
        


        #region dgvBill



        private void dgvBill_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            txtTotal.Text = getTotal().ToString();
        }

        private void dgvBill_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            txtTotal.Text = getTotal().ToString();
        }



        #endregion


        #region txtPaid


        private void txtPaid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
            if (Char.IsDigit(e.KeyChar) && txtPaid.Text == "0")
            {
                txtPaid.Text = e.KeyChar.ToString();
                txtPaid.SelectionStart = txtPaid.TextLength;
                e.Handled = true;
            }
            
        }
        private void txtPaid_TextChanged(object sender, EventArgs e)
        {

            if (rbtCash.Checked == true)
            {
                {
                    txtPaid.Text = String.Format("{0:0,0}", double.Parse(txtPaid.Text));
                    txtChange.Text = (double.Parse(txtPaid.Text) - double.Parse(txtTotal.Text)).ToString();
                    txtPaid.SelectionStart = (txtPaid.TextLength);
                }
            }
        }
        private void txtPaid_Enter(object sender, EventArgs e)
        {
            txtPaid.SelectionStart = txtPaid.TextLength;
        }

        private void txtPaid_Click(object sender, EventArgs e)
        {
            txtPaid.SelectionStart = txtPaid.TextLength;
            txtPaid.SelectAll();
        }

        #endregion


        #region txtBarcode

        private void txtBarcode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtBarcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Validate vld = new Validate();
                if (vld.Barcode(txtBarcode.Text))
                {
                    ReadBarcode();
                }
                else
                {
                    highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                    lblValidate.Text = "Mã vạch không hợp lệ, vui lòng quét lại.";
                    txtBarcode.Clear();
                    txtBarcode.Focus();
                }
            }
        }

        private void txtBarcode_TextChanged(object sender, EventArgs e)
        {
            if (txtBarcode.Text != "")
            {
                highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.None);
                lblValidate.Text = "";
            }
            else
            {
                txtTitle.Clear();
                txtCopy.Clear();
                txtDiscount.Clear();
            }
        }


        #endregion


        #region dgvBookSearch

        private void dgvBookSearch_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvBill.RowCount == 0) lblBillID.Text = ShowBillID((billDAL.GetMaxBillID() + 1));
            txtBarcode.Text = dgvBookSearch.Rows[e.RowIndex].Cells[0].Value.ToString();
            txtBarcode.ReadOnly = false;
            addMode = false;
            LoadBook();
        }

        #endregion


        private void btnLogout_Click(object sender, EventArgs e)
        {
            logout = true;
            this.Close();
        }

    
        private void txtTotal_TextChanged(object sender, EventArgs e)
        {
            if ((double.Parse(txtPaid.Text) - double.Parse(txtTotal.Text)) > 0)
            {
                txtChange.Text = (double.Parse(txtPaid.Text) - double.Parse(txtTotal.Text)).ToString();
            }
            else
                txtPaid.Text = txtTotal.Text;
        }

        public void LoaddgvBookSearch()
        {
            ProjectDAL p = new ProjectDAL();
            project = p.GetProjectByStatus();
            Project_BookDAL prboDAL = new Project_BookDAL();
            List<Book> lb = new List<Book>();
            lb = prboDAL.GetAllBookByProjectID(project.ProjectID);
            ConvertBook_SBook(lb);
        }

        public void ConvertBook_SBook(List<Book> lb)
        {
            lsb = new List<SBook>();
            SBook sb = null;
            if (lb != null)
            {
                foreach (Book b in lb)
                {
                    sb = new SBook(b);
                    lsb.Add(sb);
                }
            }
        
        }

        private void lblStaffname_TextChanged(object sender, EventArgs e)
        {

            txtBarcode.Focus();
            dgvBookSearch.DataSource = lsb;
            dgvBookSearch.Columns[0].Width = 98;
            dgvBookSearch.Columns[1].Width = 247;
            dgvBookSearch.Columns[2].Width = 100;
            dgvBookSearch.Columns[3].Width = 85;
        }


        private void textBoxX1_TextChanged(object sender, EventArgs e)
        {
            Project_BookDAL pbDAL = new Project_BookDAL();
            List<Book> lb = new List<Book>();
            lb = pbDAL.GetAllBookByProjectIDAndBookTitle(project.ProjectID, txtBookTitle.Text);
            SBook sb = null;
            if (lb == null)
            {
                dgvBookSearch.DataSource = new List<SBook>();
            }
            else
            {
                lsb = new List<SBook>();
                foreach (Book b in lb)
                {
                    sb = new SBook(b);
                    lsb.Add(sb);
                }
                dgvBookSearch.DataSource = lsb;
            }
        }


        private void tabBillHistory_Click(object sender, EventArgs e)
        {
            List<Bill> lbi = new List<Bill>();
            lbi = billDAL.GetAllBillByProjectID(project.ProjectID);
            List<BillView> lbv = new List<BillView>();
            if (lbi != null)
            {
                BillView bv;
                for (int i = 0; i < lbi.Count; i++)
                {
                    bv = new BillView(lbi[i]);
                    lbv.Add(bv);
                }
            }
            dgvBillHistory.DataSource = lbv;
            dgvBillHistory.Columns[0].Width = 80;
            dgvBillHistory.Columns[1].Width = 90;
            dgvBillHistory.Columns[2].Width = 90;
            dgvBillHistory.Columns[3].Width = 90;
            dgvBillHistory.Columns[4].Width = 150;
            dgvBillHistory.Columns[5].Width = 120;
            dgvBillHistory.Columns[6].Width = 120;
            dgvBillHistory.Columns[7].Width = 120;
            superTabControl2.SelectedTab = tabSearch;
        }


        public string ShowBillID(int id)
        {
            string result = "0000000" + id.ToString();
            return result.Substring(result.Length - 7);
        }

        private void tabEdit_Click(object sender, EventArgs e)
        {
            lblBillHistoryID.Text = ShowBillID(Convert.ToInt16(dgvBillHistory.SelectedRows[0].Cells[0].Value));
            dgvBillHistory.Enabled = false;
        }

        private void tabSearch_Click(object sender, EventArgs e)
        {
            dgvBillHistory.Enabled = true;
        }

        private void cboDate_ValueChanged(object sender, EventArgs e)
        {
            FilterBillHistory();
        }

        public void FilterBillHistory()
        {
            List<Bill> lbi = new List<Bill>();
            DateTime date = new DateTime();
            if (cboDate.Value != date)
            {
                date = cboDate.Value;
            }
            else
            {
                date = DateTime.Parse("1/1/1800");
            }
            int cid = 0;
            if (txtCustomerID.Text !="") cid = int.Parse(txtCustomerID.Text);
            int bid = 0;
            if (txtBillID.Text != "") bid = int.Parse(txtBillID.Text);
            int sid = 0;
            if (txtStaffID.Text != "") sid = int.Parse(txtStaffID.Text);
            int ftotal = 0;
            if (txtFirstPrice.Text != "") ftotal = int.Parse(txtFirstPrice.Text);
            int ltotal = 0;
            if (txtLastPrice.Text != "") ltotal = int.Parse(txtLastPrice.Text);
            lbi = billDAL.GetAllBillByFilter(project.ProjectID, bid, cid, sid, date, ftotal, ltotal);
            List<BillView> lbv = new List<BillView>();
            BillView bv;
            for (int i = 0; i < lbi.Count; i++)
            {
                bv = new BillView(lbi[i]);
                lbv.Add(bv);
            }
            dgvBillHistory.DataSource = lbv;
        }

        private void txtFirstPrice_Leave(object sender, EventArgs e)
        {
            FilterBillHistory();
        }

        private void txtLastPrice_Leave(object sender, EventArgs e)
        {
            FilterBillHistory();
        }

        private void txtCustomerID_Leave(object sender, EventArgs e)
        {
            FilterBillHistory();
        }

        private void txtBillID_Leave(object sender, EventArgs e)
        {
            FilterBillHistory();
        }

        private void txtStaffID_Leave(object sender, EventArgs e)
        {
            FilterBillHistory();
        }

        private void btnClearAllFilter_Click(object sender, EventArgs e)
        {
            cboDate.ResetValue();
            txtFirstPrice.Clear();
            txtCustomerID.Clear();
            txtLastPrice.Clear();
            txtStaffID.Clear();
            txtBillID.Clear();
            FilterBillHistory();
        }

        private void txtFirstPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true; 
            }
        }

        private void txtLastPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtCustomerID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtBillID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtStaffID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtEditCustomerID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtEditCustomerID_TextChanged(object sender, EventArgs e)
        {
            if (txtEditCustomerID.TextLength < 9)
            {
                highlighter1.SetHighlightColor(txtEditCustomerID, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
            }
            else
            {
                highlighter1.SetHighlightColor(txtEditCustomerID, DevComponents.DotNetBar.Validator.eHighlightColor.Blue);
            }
        }

        private void txtEditCustomerID_Leave(object sender, EventArgs e)
        {
            highlighter1.SetHighlightColor(txtEditCustomerID, DevComponents.DotNetBar.Validator.eHighlightColor.None);
        }

        private void dgvBillHistory_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                List<Bill_Book> lbb = new List<Bill_Book>();
                Bill_BookDAL bbDAL = new Bill_BookDAL();
                lbb = bbDAL.GetBill_BookByBillID(Convert.ToInt16(dgvBillHistory[0, e.RowIndex].Value));
                if (lbb != null)
                {
                    List<Bill_BookView> lbbv = new List<Bill_BookView>();
                    Bill_BookView bbv;
                    for (int i = 0; i < lbb.Count; i++)
                    {
                        bbv = new Bill_BookView(lbb[i]);
                        lbbv.Add(bbv);
                    }
                    billHisEdittingRow = e.RowIndex;
                    dgvBillDetail.DataSource = lbbv;
                    dgvBillDetail.Columns[0].Width = 80;
                    dgvBillDetail.Columns[1].Width = 150;
                    dgvBillDetail.Columns[2].Width = 60;
                    dgvBillDetail.Columns[3].Width = 60;
                    dgvBillDetail.Columns[4].Width = 60;
                }
                else
                {
                    dgvBillDetail.DataSource = new List<Bill_BookView>();
                }
            }
        }

        private void txtCopy_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtCopy_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                if (txtCopy.Text == "")
                {
                    highlighter1.SetHighlightColor(txtCopy, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                    txtCopy.Focus();
                    txtCopy.SelectAll();
                    lblValidate.Text = "Số lượng nhập vào không hợp lệ";
                }
                else
                {
                    if (txtBarcode.ReadOnly != true)
                    {
                        double discount = 0;
                        bool skip = false;
                        if (txtDiscount.Text != "")
                        {
                            try
                            {
                                discount = Convert.ToDouble(txtDiscount.Text);
                            }
                            catch
                            {
                                skip = true;
                                lblValidate.Text = "Chiết khấu không hợp lệ";
                                txtDiscount.Focus();
                                txtDiscount.SelectAll();
                                highlighter1.SetHighlightColor(txtDiscount, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                            }
                        }
                        if (!skip)
                        {
                            int id = GetBookIndex_dgvBill(book.ISBN);
                            if (id == dgvBill.RowCount || dgvBill.RowCount == 0)
                            {
                                if (txtCopy.Text.Length>4||Convert.ToInt64(txtCopy.Text) > (new Project_BookDAL()).GetQuatityInWareHouseBookByBookID(project.ProjectID, book.BookID))
                                {
                                    txtCopy.Focus();
                                    txtCopy.SelectAll();
                                    lblValidate.Text = "Số lượng nhiều hơn số lượng có trong kho.";
                                }
                                else
                                {
                                    Bill_Book bb = new Bill_Book(null, book, 0, 0);
                                    billdetail.Add(bb);
                                    AddBookToBill(book.ISBN, book.Title, Convert.ToInt16(txtCopy.Text), book.Price, discount);
                                }
                            }
                            else
                            {
                                if (Convert.ToInt16(txtCopy.Text) > (new Project_BookDAL()).GetQuatityInWareHouseBookByBookID(project.ProjectID, book.BookID) - Convert.ToInt16(dgvBill.Rows[id].Cells[3].Value))
                                {
                                    txtCopy.Focus();
                                    txtCopy.SelectAll();
                                    lblValidate.Text = "Số lượng nhiều hơn số lượng có trong kho.";
                                }
                                else
                                {
                                    Bill_Book bb = new Bill_Book(null, book, 0, 0);
                                    billdetail.Add(bb);
                                    AddBookToBill(book.ISBN, book.Title, Convert.ToInt16(txtCopy.Text), book.Price, discount);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (txtCopy.Text!="0")
                        {
                            dgvBill[3, editRow].Value = Convert.ToInt16(txtCopy.Text);
                        }
                        else
                        {
                            dgvBill.Rows.RemoveAt(editRow);
                        }
                    }
                    if (highlighter1.GetHighlightColor(txtCopy) != DevComponents.DotNetBar.Validator.eHighlightColor.Red)
                    {
                        if (lblValidate.Text == "Mã sách chưa được kiểm kê!")
                        {
                            Project_Book pb = new Project_Book(project, book, 1000, 0, 0, false);
                            pbDAL.CreateProject_Book(pb);
                        }
                        if (lblValidate.Text != "Số lượng nhiều hơn số lượng có trong kho.")
                        {
                            book = null;
                            lblValidate.Text = "";
                            txtCopy.Clear();
                            txtTitle.Clear();
                            txtDiscount.Clear();
                            txtBarcode.ReadOnly = false;
                            txtBarcode.Clear();
                            txtBarcode.Focus();
                        }
                    }
                }
            }
            else
            {
                if (e.KeyCode == Keys.Escape)
                {
                    txtBarcode.ReadOnly = false;
                    txtCopy.Clear();
                    txtTitle.Clear();
                    txtBarcode.Clear();
                    txtBarcode.Focus();
                }
            }
        }

        private void dgvBill_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (dgvBill.RowCount == 0)
            {
                billdetail = new List<Bill_Book>();
            }
            else
            {
                for (int i = 1; i <= dgvBill.RowCount; i++)
                {
                    dgvBill.Rows[i - 1].Cells[0].Value = i;
                }
                txtTotal.Text = getTotal().ToString();
                billdetail.RemoveAt(e.RowIndex);
            }
            dgvBill.Refresh();
        }

        private void dgvBill_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if ((e.ColumnIndex == 7))
                {
                    if (dgvBill.Rows[e.RowIndex].DefaultCellStyle.BackColor != Color.LightGreen)
                    {
                        dgvBill.Rows.RemoveAt(e.RowIndex);
                    }
                    else
                    {
                        if (MessageBox.Show("Bạn có chắc muốn xóa quyển sách này khỏi hóa đơn không", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                        {
                            dgvBill.Rows.RemoveAt(e.RowIndex);
                        }
                    }
                }
                else
                {
                    txtBarcode.ReadOnly = true;
                    txtBarcode.Text = dgvBill[1, e.RowIndex].Value.ToString();
                    txtTitle.Text = dgvBill[2, e.RowIndex].Value.ToString();
                    txtCopy.Text = dgvBill[3, e.RowIndex].Value.ToString();
                    txtDiscount.Text = dgvBill[5, e.RowIndex].Value.ToString();
                    txtCopy.Focus();
                    txtCopy.SelectAll();
                    editRow = e.RowIndex;
                }
            }
        }

        private void btnServerConfig_Click(object sender, EventArgs e)
        {
            Process.Start("serverconfig.exe");
        }

        private void txtCopy_TextChanged(object sender, EventArgs e)
        {
            highlighter1.SetHighlightColor(txtCopy, DevComponents.DotNetBar.Validator.eHighlightColor.None);
            lblValidate.Text = "";
        }

        private void rbtBonus_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtBonus.Checked)
            {
                if (!((lblCustomerID.Text != "000000000") && ((Convert.ToInt32(lblCustomerBonus.Text) * 0.05) >= Convert.ToInt32(txtTotal.Text))))
                {
                    MessageBox.Show("Số điểm hiện tại của bạn chưa thể thanh toán hóa đơn này");
                    rbtCash.Checked = true;
                }
            }
        }

        private void dgvBill_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                dgvBill[e.ColumnIndex, e.RowIndex].Selected = true;
                RightClickMenu.Enabled = true;
                row = e.RowIndex;
            }
        }

        private void dgvBill_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {                
                RightClickMenu.Enabled = false;
            }
        }

        private void btnEditDiscount_Click(object sender, EventArgs e)
        {
            if (row >= 0)
            {
                txtBarcode.ReadOnly = true;
                txtBarcode.Text = dgvBill[1, row].Value.ToString();
                txtTitle.Text = dgvBill[2, row].Value.ToString();
                txtCopy.Text = dgvBill[3, row].Value.ToString();
                txtDiscount.Text = dgvBill[5, row].Value.ToString();
                txtCopy.Focus();
                txtCopy.SelectAll();
                editRow = row;
                row = -1;
            }
        }

        private void txtDiscount_TextChanged(object sender, EventArgs e)
        {
            highlighter1.SetHighlightColor(txtDiscount, DevComponents.DotNetBar.Validator.eHighlightColor.None);
            lblValidate.Text = "";
        }

        private void btnDeleteBook_Click(object sender, EventArgs e)
        {
            if (row >= 0)
            {
                if (dgvBill.Rows[row].DefaultCellStyle.BackColor != Color.LightGreen)
                {
                    dgvBill.Rows.RemoveAt(row);
                    row = -1;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            oBill = billDAL.GetBillByID(Convert.ToInt16(lblBillHistoryID.Text));
            CustomerDAL cDAL = new CustomerDAL();
            Customer c = cDAL.GetCustomerByCMND(Convert.ToInt32(txtEditCustomerID.Text));
            if (c != null)
            {
                if (oBill.Customer.CustomerID == 1)
                {
                    DialogResult r = MessageBox.Show("Bạn có muốn thay đổi người sở hữu hóa đơn này thành " + c.CName + " hay không?", "Thay đổi thông tin hóa đơn", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (r == DialogResult.Yes)
                    {
                        c.Points = c.Points + Convert.ToInt32(oBill.Total);
                        oBill.Customer = c;
                        billDAL.UpdateBill(oBill);
                        cDAL.UpdateCustomer(c);
                        txtCustomerID.Clear();
                        tabSearch.Focus();
                    }
                    else
                    {
                        txtCustomerID.Focus();
                        txtCustomerID.SelectAll();
                    }
                }
                else
                {
                    MessageBox.Show("Hóa đơn này đó có người sở hữu, bạn không có quyền thay đổi");
                }
            }
            else
            {
                txtCustomerID.Focus();
                txtCustomerID.SelectAll();
                highlighter1.SetHighlightColor(txtCustomerID,DevComponents.DotNetBar.Validator.eHighlightColor.Red);
            }
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!logout)
            {
                Application.Exit();
            }
        }

        private void txtChange_TextChanged(object sender, EventArgs e)
        {
            txtChange.Text = String.Format("{0:0,0.0}", double.Parse(txtChange.Text));
        }

        private void btnReprint_Click(object sender, EventArgs e)
        {
            PrintDocument doc = new PrintDocument();
            doc.PrintPage += new PrintPageEventHandler(Doc_reprint);
            doc.Print();
        }

        private void Doc_reprint(object sender, PrintPageEventArgs e)
        {
            Font time = new Font("Times New Roman", 11);
            Font time2 = new Font("Consolas", 7);
            Graphics g = e.Graphics;
            Image logo = System.Drawing.Bitmap.FromFile(@"logo.bmp");
            float lpg = 0;
            float ypos = 0;
            float tmargin = e.MarginBounds.Top;
            lpg = e.MarginBounds.Height / time.GetHeight(g);

            g.DrawImage(logo, 7, 15);
            g.DrawString("Công ty Cổ Phần COCBOOK", time, Brushes.Black, 5, 75, new StringFormat());
            ypos = 75 + time.GetHeight(g);
            g.DrawString("   www.cocbook.vn | fb/cocbook", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g) + 5;
            g.DrawString("     0939646679 | 0839918488", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g) + 5;
            g.DrawString("_________________________________", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Nhân viên: " + lblStaffname.Text, time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Tên hàng |CK |SL |Giá |Thành tiền", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("----------------------------------", time2, Brushes.Black, 5, ypos, new StringFormat());
            /////////////////////////

            int total = 0;
            for (int i = 0; i < dgvBillDetail.RowCount; i++)
            {
                ypos = ypos + time2.GetHeight(g);
                if (dgvBillDetail[1, i].Value.ToString().Length < 30)
                {
                    g.DrawString(dgvBillDetail[1, i].Value.ToString() + "... ", time2, Brushes.Black, 5, ypos, new StringFormat());
                }
                else
                {
                    g.DrawString(dgvBillDetail[1, i].Value.ToString().Substring(0, 30) + "... ", time2, Brushes.Black, 5, ypos, new StringFormat());
                }
                total += Convert.ToInt32(dgvBillDetail[4, i].Value);
                ypos = ypos + time2.GetHeight(g);
                g.DrawString("          " + dgvBillDetail[3, i].Value.ToString() + "  " + dgvBillDetail[4, i].Value.ToString() + "  " + dgvBillDetail[2, i].Value.ToString() + "  " +
                            (Convert.ToInt32(dgvBillDetail[2, i].Value) * Convert.ToInt32(dgvBillDetail[4, i].Value) * (100 - Convert.ToInt32(dgvBillDetail[3, i].Value))/100).ToString(), time2, Brushes.Black, 5, ypos, new StringFormat());
            }
            /////////////////////////
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("-------------------------------------", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Tổng:       " + total + "         " + dgvBillHistory[5, billHisEdittingRow].Value.ToString(), time, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time.GetHeight(g);
            g.DrawString(dgvBillHistory[4, billHisEdittingRow].Value.ToString(), time2, Brushes.Black, 5, ypos, new StringFormat());
            Image billCode = Code128Rendering.MakeBarcodeImage(ShowBillID(Convert.ToInt32(dgvBillHistory[0, billHisEdittingRow].Value)), 1, true);
            ypos = ypos + time2.GetHeight(g);
            g.DrawImage(billCode, 10, ypos);
            ypos = ypos + 20;
            g.DrawString(ShowBillID(Convert.ToInt32(dgvBillHistory[0, billHisEdittingRow].Value)), time2, Brushes.Black, 5, ypos, new StringFormat());

            string customerId = ShowCustomerID(Convert.ToInt32(dgvBillHistory[2, billHisEdittingRow].Value));
            billCode = Code128Rendering.MakeBarcodeImage(customerId, 1, true);

            ypos = ypos + time2.GetHeight(g) + 5;
            g.DrawImage(billCode, 10, ypos);
            ypos = ypos + 20;
            g.DrawString(customerId, time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("_______________________________________", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g)+5;
            g.DrawString("Cocbook.vn Cảm ơn bạn đã mua sách", time2, Brushes.Black, 5, ypos, new StringFormat());
        }




    }
}